package cn.com.common.job.task;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.com.common.config.FileUploadProperties;
import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasOilpriceEntity;
import cn.com.gas.entity.GasServerAreaEntity;
import cn.com.gas.entity.GasServerChannelEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeEntity;
import cn.com.gas.entity.GasStaytimeHistoryEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasOilpriceService;
import cn.com.gas.service.GasServerAreaService;
import cn.com.gas.service.GasServerChannelService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeHistoryService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.gas.service.GasStaytimeService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.thirdparty.entity.ProvinceGasStaytimeResultEntity;
import cn.com.thirdparty.entity.ZnGasStation;
import cn.com.thirdparty.mapper.GasDetectionSqlMapper;
import cn.com.thirdparty.mapper.ProvinceGasStaytimeResultMapper;
import cn.com.thirdparty.mapper.ZnGasStationMapper;
// import cn.com.thirdparty.service.VSscllService;
import cn.com.util.DateUtils;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasStaytimeProcessTask")
@DisallowConcurrentExecution
public class GasStaytimeProcessTask {

	@Value("${gasstation.timedTask.gasStaytimeProcessTask}")
	private String gasStaytimeProcessTask;

	@Value("${gasstation.gasCarRuleids}")
	private String gasCarRuleids;
	
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GasStaytimeService gasStaytimeService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	
	@Autowired
	private ProvinceGasStaytimeResultMapper provinceGasStaytimeResultMapper;
	
	@Autowired
	private GasStaytimeHistoryService gasStaytimeHistoryService;
	@Autowired
	private GasOilpriceService gasOilpriceService;
	@Autowired
	private FileUploadProperties fileUploadProperties;

	@Autowired
	private GasServerAreaService gasServerAreaService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasServerChannelService gasServerChannelService;
	@Autowired
	private SysParameterService sysParameterService;
	
	
	
	/*@Autowired 
	private VSscllService vSscllService;
	 
	@Autowired
	private DeptService deptService;*/
	
	@Autowired
	private GasDetectionSqlMapper gasDetectionSqlMapper;
	@Autowired
	private ZnGasStationMapper znGasStationMapper;
	
	LocalDate now = LocalDate.now();
	LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
	LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void run(String params) throws Exception {
		
		String pushFlag = "N";
		SysParameterEntity parameterEntity106 = sysParameterService.getById("parameter106");
		SysParameterEntity parameterEntity102 = sysParameterService.getById("parameter102");

		if(TsBqUtils.isNotNull(parameterEntity106)){
			pushFlag = parameterEntity106.getParameter();
		}
		logger.debug("gasStaytimeProcessTask给省平台推送标志，标志为：{}", pushFlag);

		logger.debug("application参数为gasStaytimeProcessTask：{}", gasStaytimeProcessTask);

		if (gasStaytimeProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasStaytimeProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasStaytimeProcessTask定时任务");
		}

		Date date = new Date();
		logger.debug("gasStaytimeProcessTask定时任务正在执行，参数为：{}", params);
		logger.debug("gasStaytimeProcessTask定时任务正在执行，时间：{}", date);

		int parameter101 = 30;
		String _parameter103 = "N";

		SysParameterEntity parameter = sysParameterService.getById("parameter101");

		SysParameterEntity parameter103 = sysParameterService.getById("parameter103");

		if (TsBqUtils.isNotNull(parameter)) {
			try {
				parameter101 = Integer.parseInt(parameter.getParameter());
				logger.debug("gasStaytimeProcessTask定时任务配置车辆进入时间和离开时间参数控制，参数为：{}", parameter101);
			} catch (Exception e) {
				logger.debug("转换异常：" + e.getMessage());
			}
		}

		if (TsBqUtils.isNotNull(parameter103)) {
			try {
				_parameter103 = parameter103.getParameter();
				logger.debug("gasStaytimeProcessTask定时任务配置车辆进入时间和离开时间比较控制油价浮动参数，参数为：{}", _parameter103);
			} catch (Exception e) {
				logger.debug("转换异常：" + e.getMessage());
			}
		}

		Page page = new Page(1, 500); // 每次处理500条
		page.setSearchCount(false); // 可选，是否进行 count 查询，默认为 true，若不需要 count，设置为

		LambdaQueryWrapper<GasStaytimeEntity> queryWrapper = Wrappers.lambdaQuery();

		// 筛选口径逻辑
		queryWrapper.isNotNull(GasStaytimeEntity::getImage);

		// queryWrapper.isNotNull(GasStaytimeEntity::getMessageDisappear);
		queryWrapper.isNotNull(GasStaytimeEntity::getMessageAppear);
		// queryWrapper.ne(GasStaytimeEntity::getMessageDisappear, "");
		queryWrapper.ne(GasStaytimeEntity::getMessageAppear, "");
		queryWrapper.orderByDesc(GasStaytimeEntity::getCreateTime);
		
		IPage<GasStaytimeEntity> iPage = gasStaytimeService.page(page, queryWrapper);
		List<GasStaytimeEntity> list = iPage.getRecords();

		LambdaQueryWrapper<GasOilpriceEntity> queryWrapper3 = Wrappers.lambdaQuery();
		queryWrapper3.orderByDesc(GasOilpriceEntity::getCreateTime);
		GasOilpriceEntity gasOilpriceEntity = gasOilpriceService.getOne(queryWrapper3);

		if (TsBqUtils.isNotNull(list)) {
			for (GasStaytimeEntity gasStaytimeEntity : list) {
				String id = gasStaytimeEntity.getId();

				String regionCode = gasStaytimeEntity.getField2();
				String deviceId = gasStaytimeEntity.getField3();

				if (TsBqUtils.isNotNull(regionCode) && TsBqUtils.isNotNull(deviceId)) {
					// 大模型 逻辑
					String messageRuleid = gasStaytimeEntity.getMessageRuleid();
					GasStaytimeResultEntity gasStaytimeResultEntity = new GasStaytimeResultEntity();

					BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeResultEntity);
					// 判断油品
					if (messageRuleid.equals(Constants.GAS_CAR_SMALL)) {

						gasStaytimeResultEntity.setOils("汽油");
						gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getGasoline());
					} else if (messageRuleid.equals(Constants.GAS_CAR_MOTO)) {

						gasStaytimeResultEntity.setOils("汽油");
						gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getGasolineMoto());

					} else {
						gasStaytimeResultEntity.setOils("柴油");
						gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getDiesel());

					}

					gasStaytimeResultEntity.setStationId(regionCode);
					gasStaytimeResultEntity.setField5(deviceId);

					// 数据入库
					gasStaytimeResultService.save(gasStaytimeResultEntity);

				} else {
					// 传统模型 逻辑
					String messageAppear = gasStaytimeEntity.getMessageAppear();
					String messageDisappear = gasStaytimeEntity.getMessageDisappear();
					String messageRulename = gasStaytimeEntity.getMessageRulename();
					String messageLabel = gasStaytimeEntity.getMessageLabel();
					String image = gasStaytimeEntity.getImage();
					String messageRuleid = gasStaytimeEntity.getMessageRuleid();

					if (TsBqUtils.isNull(messageDisappear)) {
						
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

						String _messageAppear = messageAppear.substring(0, 7) + "-01 00:00:00";
						Date messageAppearDate = format.parse(_messageAppear); 
						
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(messageAppearDate);
						calendar.add(Calendar.MONTH, 1);
				        String messageAppearNext = format.format(calendar.getTime());
				        String _messageAppearNext = messageAppearNext.substring(0, 7) + "-01 23:59:59";
				        Date messageAppearNextDate = format.parse(_messageAppearNext); 
						
						// 补充第二章图片
						LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapperResult = Wrappers.lambdaQuery();
						queryWrapperResult.eq(GasStaytimeResultEntity::getMessageLabel, messageLabel);
						// 根据 messageAppear 获取月份
				        // Date firstDayOfMonthDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
				        // Date firstDayOfNextMonthDate = Date.from(firstDayOfNextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
				        
				        queryWrapperResult.ge(GasStaytimeResultEntity::getMessageDisappear, messageAppearDate);
				        queryWrapperResult.lt(GasStaytimeResultEntity::getMessageDisappear, messageAppearNextDate);

						List<GasStaytimeResultEntity> resultList = gasStaytimeResultService.list(queryWrapperResult);

						if (TsBqUtils.isNotNull(resultList)) {
							logger.debug("补充第二章图片,合并数据label:" + messageLabel);

							GasStaytimeResultEntity entity = resultList.get(0);
							entity.setImage1(image);
							entity.setUpdateTime(date);
							LambdaQueryWrapper<GasStaytimeResultEntity> updateWrapper = Wrappers.lambdaQuery();
							updateWrapper.eq(GasStaytimeResultEntity::getId, entity.getId());
							updateWrapper.eq(GasStaytimeResultEntity::getMessageDisappear, entity.getMessageDisappear());

							gasStaytimeResultService.update(entity,updateWrapper);
							
							
							
							gasStaytimeService.realDelete(id);
						}else{
							String createTime = DateUtils.format(date, DateUtils.DATE_TIME_PATTERN_1);
							long _l = TsBqUtils.dateSubtract(createTime, messageAppear);
							logger.info("gasStaytimeProcessTask定时任务-当前时间与messageAppear差:" + _l);
							if (_l > 60*60*24*2) {
								GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
								gasStaytimeEntity.setHandleFlag("当前时间与messageAppear差：" + _l + "秒");
								logger.info("当前时间于messageAppear差，超过 60*60*24*2 秒，处理数据！");
								BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
								gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
								gasStaytimeService.realDelete(id);
							}
						}
					} else {
						List<String> listRuleid = new ArrayList<>();
						if(TsBqUtils.isNotNull(gasCarRuleids)){
							String[] split = gasCarRuleids.split(",");
							for (String string : split) {
								listRuleid.add(string);
							}
						}else{
							listRuleid.add(Constants.GAS_CAR_SMALL);
							listRuleid.add(Constants.GAS_CAR_BIG);
							listRuleid.add(Constants.GAS_CAR_MOTO);
							listRuleid.add(Constants.GAS_CAR_TRUCK);
							listRuleid.add(Constants.GAS_CAR_PROJECT);

							listRuleid.add(Constants.GAS_CAR_FARMING);
							listRuleid.add(Constants.GAS_CAR_LIGHTTRUCK);
						}
						
						String messageAreanumber = gasStaytimeEntity.getMessageAreanumber();

						if (TsBqUtils.isConvertibleToInt(messageAreanumber)) {
							int messageAreanumberInt = Integer.parseInt(messageAreanumber);

							if (TsBqUtils.isNotNull(messageRulename) && TsBqUtils.isNotNull(messageAppear)
									&& TsBqUtils.isNotNull(messageDisappear) && TsBqUtils.isNotNull(messageRulename)
									&& TsBqUtils.isNotNull(image) && TsBqUtils.isNotNull(messageAreanumber)
									&& listRuleid.contains(messageRuleid) && messageAreanumberInt < 30) {

								if (TsBqUtils.isDate(messageAppear) && TsBqUtils.isDate(messageDisappear)) {

									if (TsBqUtils.dateSubtract(messageDisappear, messageAppear, parameter101)) {

										GasStaytimeResultEntity gasStaytimeResultEntity = new GasStaytimeResultEntity();

										if (gasStaytimeEntity.getImage().contains("data:image")) {
											String imgName = TsBqUtils.getUUID();
											String createTime = DateUtils.format(date, DateUtils.DATEPATTERN);

											String base64Extension = TsBqUtils
													.getBase64Extension(gasStaytimeEntity.getImage());
											if (TsBqUtils.isNotNull(base64Extension)) {
												String path = fileUploadProperties.getPath() + createTime
														+ File.separator;
												String url = fileUploadProperties.getUrl() + File.separator + createTime
														+ File.separator + imgName + "." + base64Extension;
												if (TsBqUtils.decodeBase64ToImage(gasStaytimeEntity.getImage(), path,
														imgName + "." + base64Extension)) {
													gasStaytimeEntity.setImage(url);
												} else {
													GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
													gasStaytimeEntity.setHandleFlag("decodeBase64ToImage图片处理失败");
													logger.info("decodeBase64ToImage图片处理失败");
													BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
													gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
													gasStaytimeService.realDelete(id);
												}
											} else {
												GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
												gasStaytimeEntity.setHandleFlag("getBase64Extension文件后缀处理失败");
												logger.info("getBase64Extension文件后缀处理失败");
												BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
												gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
												gasStaytimeService.realDelete(id);
											}
										}

										BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeResultEntity);

										long l = TsBqUtils.dateSubtract(messageDisappear, messageAppear);
										logger.info("gasStaytimeProcessTask定时任务-dateSubtract入区和出区时间差:" + l);
										String gasoline = gasOilpriceEntity.getGasoline();
										// 判断油品
										if (messageRuleid.equals(Constants.GAS_CAR_SMALL)) {
											gasStaytimeResultEntity.setOils("汽油");
											if (_parameter103.equals("Y")) {
												BigDecimal _result = new BigDecimal(gasoline);
												// 180 秒 以下 220 1 700 基数
												// 180 秒 - 300 秒 286 1.3 900
												// 300 秒以上 330 1.5 1400 2
												if (l < 180) {
													gasoline = _result.toString();
												} else if (l >= 180 && l <= 300) {
													gasoline = (_result.multiply(new BigDecimal("1.3")).setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
												} else {
													gasoline = (_result.multiply(new BigDecimal("1.5")).setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
												}
											}
											logger.info("gasStaytimeProcessTask定时任务-入区和出区时间差:" + l + "====" + gasoline
													+ "====" + messageDisappear);

											gasStaytimeResultEntity.setPrice(gasoline);
										} else if (messageRuleid.equals(Constants.GAS_CAR_MOTO)) {

											gasStaytimeResultEntity.setOils("汽油");
											gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getGasolineMoto());

										} else if (messageRuleid.equals(Constants.GAS_CAR_FARMING)) {
											// 农用车
											gasStaytimeResultEntity.setOils("汽油");
											gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getGasolineFarming());

										} else if (messageRuleid.equals(Constants.GAS_CAR_LIGHTTRUCK)) {
											// 轻卡
											gasStaytimeResultEntity.setOils("汽油");
											gasStaytimeResultEntity.setPrice(gasOilpriceEntity.getGasolineLighttruck());

										} else {
											gasStaytimeResultEntity.setOils("柴油");

											String diesel = gasOilpriceEntity.getDiesel();
											if (_parameter103.equals("Y")) {
												BigDecimal _result = new BigDecimal(diesel);

												// 180 秒 以下 220 1 700 基数
												// 180 秒 - 300 秒 286 1.3 900
												// 300 秒以上 330 1.5 1400 2

												if (l < 180) {
													diesel = _result.toString();
												} else if (l >= 180 && l <= 300) {
													diesel = (new BigDecimal("900")).toString();
												} else {
													diesel = (_result.multiply(new BigDecimal("2")).setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
												}
											}
											logger.info("gasStaytimeProcessTask定时任务-入区和出区时间差:" + l + "====" + diesel + "====" + messageDisappear);
											gasStaytimeResultEntity.setPrice(diesel);
										}

										// 匹配税务机关 和 加油站ID
										if (TsBqUtils.isNotNull(deviceId)) {
											// 走匹配新的逻辑 通过camid 匹配上级
											GasStationinfoEntity stationinfo = gasStationinfoService.getById(deviceId);

											if (TsBqUtils.isNotNull(stationinfo)) {
												String pid = stationinfo.getPid();

												gasStaytimeResultEntity.setStationId(pid);
												gasStaytimeResultEntity.setField5(deviceId);
												GasStationinfoEntity stationinfoPid = gasStationinfoService
														.getById(pid);
												String taxorgcode = stationinfoPid.getTaxorgcode();
												String oils = gasStaytimeResultEntity.getOils();

												// 根据油站 重新匹配 油价 和 油品
												String gastype = stationinfoPid.getGastype();
												String _gasoline = stationinfoPid.getGasoline();
												String _gasolineMoto = stationinfoPid.getGasolineMoto();
												String _gasolineFarming = stationinfoPid.getGasolineFarming();
												String _gasolineLighttruck = stationinfoPid.getGasolineLighttruck();
												String _diesel = stationinfoPid.getDiesel();

												if (TsBqUtils.isNotNull(gastype)) {
													if (gastype.equals("普通站")) {

													} else if (gastype.equals("汽油站")) {
														gasStaytimeResultEntity.setOils("汽油");

													} else if (gastype.equals("柴油站")) {
														gasStaytimeResultEntity.setOils("柴油");

													}
												}

												if (messageRuleid.equals(Constants.GAS_CAR_SMALL)) {
													if (TsBqUtils.isNotNull(_gasoline)) {
														gasStaytimeResultEntity.setPrice(_gasoline);
													}

												} else if (messageRuleid.equals(Constants.GAS_CAR_MOTO)) {
													// 摩托车
													if (TsBqUtils.isNotNull(_gasolineMoto)) {
														gasStaytimeResultEntity.setPrice(_gasolineMoto);
													}

												} else if (messageRuleid.equals(Constants.GAS_CAR_FARMING)) {
													// 农用车
													if (TsBqUtils.isNotNull(_gasolineFarming)) {
														gasStaytimeResultEntity.setPrice(_gasolineFarming);
													}

												} else if (messageRuleid.equals(Constants.GAS_CAR_LIGHTTRUCK)) {
													// 轻卡
													if (TsBqUtils.isNotNull(_gasolineLighttruck)) {
														gasStaytimeResultEntity.setPrice(_gasolineLighttruck);
													}

												} else {
													if (TsBqUtils.isNotNull(_diesel)) {
														gasStaytimeResultEntity.setPrice(_diesel);
													}

												}

												// 襄都区所有站设置为汽油
												if ("11305020000".equals(taxorgcode) && "柴油".equals(oils)) {
													gasStaytimeResultEntity.setOils("汽油");
													gasStaytimeResultEntity.setPrice(gasoline);
												}

											} else {
												logger.info(
														"gasStaytimeProcessTask定时任务-未匹配到加油站(通过camid匹配逻辑):" + deviceId);
											}

										} else {

											String messageChannel = gasStaytimeResultEntity.getMessageChannel();

											String fromTopic = gasStaytimeResultEntity.getFromTopic();

											LambdaQueryWrapper<GasServerChannelEntity> serverChannelQueryWrapper = Wrappers
													.lambdaQuery();

											serverChannelQueryWrapper.eq(GasServerChannelEntity::getTopic, fromTopic);

											List<GasServerChannelEntity> gasServerChannelList = gasServerChannelService
													.list(serverChannelQueryWrapper);

											if (TsBqUtils.isNotNull(gasServerChannelList)) {

												GasServerChannelEntity serverChannel = gasServerChannelList.get(0);
												String gasServerId = serverChannel.getId();

												LambdaQueryWrapper<GasServerAreaEntity> serverAreaQueryWrapper = Wrappers
														.lambdaQuery();

												serverAreaQueryWrapper.eq(GasServerAreaEntity::getServerChannel,
														messageChannel);
												serverAreaQueryWrapper.eq(GasServerAreaEntity::getAreaNumber,
														messageAreanumber);
												serverAreaQueryWrapper.eq(GasServerAreaEntity::getServerId,
														gasServerId);

												List<GasServerAreaEntity> serverAreaList = gasServerAreaService
														.list(serverAreaQueryWrapper);

												if (TsBqUtils.isNotNull(serverAreaList)) {
													GasServerAreaEntity gasServerAreaEntity = serverAreaList.get(0);
													String camid = gasServerAreaEntity.getCamid();
													if (TsBqUtils.isNotNull(camid)) {
														GasStationinfoEntity stationinfo = gasStationinfoService
																.getById(camid);
														if (TsBqUtils.isNotNull(stationinfo)) {
															String pid = stationinfo.getPid();
															GasStationinfoEntity stationinfo1 = gasStationinfoService
																	.getById(pid);
															if (TsBqUtils.isNotNull(stationinfo1)) {

																gasStaytimeResultEntity
																		.setStationId(stationinfo1.getId());

															} else {
																logger.info(
																		"gasStaytimeProcessTask定时任务-未匹配到加油站(stationinfo1):"
																				+ gasStaytimeResultEntity.getId());
															}
														} else {
															logger.info(
																	"gasStaytimeProcessTask定时任务-未匹配到加油站(stationinfo):"
																			+ gasStaytimeResultEntity.getId());
														}
													} else {
														logger.info("gasStaytimeProcessTask定时任务-未匹配到加油站(camid):"
																+ gasStaytimeResultEntity.getId());
													}
												} else {
													logger.info("gasStaytimeProcessTask定时任务-未匹配到加油站(GasServerArea):"
															+ gasStaytimeResultEntity.getId());

												}

											} else {
												logger.info("gasStaytimeProcessTask定时任务-未匹配到加油站(GasServer):"
														+ gasStaytimeResultEntity.getId());

											}

										}
										// 数据入本地库
										gasStaytimeResultService.save(gasStaytimeResultEntity);
										gasStaytimeService.realDelete(id);
										
										// 推送省局
										if(pushFlag.equals("Y")){
											logger.error("开始推送到省平台数据库！");
											try {
												pushProvince(gasStaytimeResultEntity);
											} catch (Exception e) {
												logger.error("推送省平台异常：" + e.getMessage());
											}
										}
										
										
										// 推送正南数据库
										/*try {
											if (TsBqUtils.isNotNull(parameterEntity102)) {
												String parameter102 = parameterEntity102.getParameter();
												if ("Y".equals(parameter102)) {

													VSscllEntity vSscll = new VSscllEntity();

													String stationId = gasStaytimeResultEntity.getStationId();
													GasStationinfoEntity gasStationinfoEntity = gasStationinfoService
															.getById(stationId);
													String taxorgcode = gasStationinfoEntity.getTaxorgcode();
													SysDept dept = deptService.getById(taxorgcode);
													String stationinfoName = gasStationinfoEntity.getName();
													vSscll.setSwjgDm(taxorgcode);
													vSscll.setSwjgMc(dept.getName()); // 税务机关名称
													vSscll.setJyzId(stationId); // 加油站编号
													vSscll.setJyzMc(stationinfoName); // 加油站名称

													vSscll.setJyzDz(""); // 加油站地址
													vSscll.setSxtLxmc(""); // 撮像头类型
													vSscll.setSxtMc(""); // 撮像头名称
													vSscll.setSxtGlid(""); // 撮像头唯一编码
													vSscll.setStatus(""); // 撮像头状态代码
													vSscll.setStatusMc(""); // 撮像头状态名称
													vSscll.setSxtId(""); // 撮像头id

													vSscll.setClassId(gasStaytimeResultEntity.getMessageRuleid()); // 车辆类型id
													vSscll.setCllxmc(gasStaytimeResultEntity.getMessageRulename()); // 车辆类型名称
													vSscll.setPhotoBase64(gasStaytimeResultEntity.getImage()); // 照片地址
													vSscll.setCreateTime(gasStaytimeResultEntity.getMessageAppear()
															.substring(0, 19)); // 开始时间
													vSscll.setStopTime(gasStaytimeResultEntity.getMessageDisappear()
															.substring(0, 19)); // 结束时间
													vSscll.setYx(""); // 油型代码
													vSscll.setXzqhDm(taxorgcode.substring(1, 7)); // 行政区划代码
													vSscll.setYxMc(gasStaytimeResultEntity.getOils()); // 油型
													vSscll.setXzqhMc(dept.getManagerName()); // 行政区划名称

													double number = Double
															.parseDouble(gasStaytimeResultEntity.getPrice());
													double roundedNumber = Math.round(number * 100) / 100.0;

													vSscll.setYj((int) Math.floor(roundedNumber)); // 金额

													boolean contains = stationinfoName.contains("中国");
													String sfsty = "否";
													if (contains) {
														sfsty = "是";
													}

													vSscll.setSfsty(sfsty); // 是否三桶油

													String image1 = gasStaytimeResultEntity.getImage1();
													if (TsBqUtils.isNull(image1)) {
														image1 = gasStaytimeResultEntity.getImage();
													}

													vSscll.setStopPhoto(image1);
													// vSscllService.saveVSscll(vSscll);
													
												}
											}
										} catch (Exception e) {
											logger.debug("写入vSscll异常:" + e.getMessage());
										}*/
										
										
										if (TsBqUtils.isNotNull(parameterEntity102)) {
											String parameter102 = parameterEntity102.getParameter();
											if ("Y".equals(parameter102)) {
												logger.error("开始推送到正南数据库！");
												try {
													String stationId = gasStaytimeResultEntity.getStationId();
													GasStationinfoEntity gasStationinfoEntity = gasStationinfoService.getById(stationId);

													pushZN(gasStaytimeResultEntity, messageDisappear, messageAppear,messageRuleid,gasStationinfoEntity);
												} catch (Exception e) {
													logger.debug("写入gas_detection_out_异常:" + e.getMessage());
												}
											}
										}
										
										
										
										
									} else {

										GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
										gasStaytimeEntity.setHandleFlag("进入和出去时间间隔较短");

										logger.info("进入和出去时间间隔较短,messageAppear()::messageDisappear"
												+ gasStaytimeEntity.getMessageAppear() + "::"
												+ gasStaytimeEntity.getMessageDisappear());

										BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
										gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
										gasStaytimeService.realDelete(id);
									}

								} else {
									GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
									gasStaytimeEntity.setHandleFlag("不符合日期数据类型");

									logger.info("isDate不符合日期数据类型,messageAppear()::messageDisappear"
											+ gasStaytimeEntity.getMessageAppear() + "::"
											+ gasStaytimeEntity.getMessageDisappear());
									BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
									gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
									gasStaytimeService.realDelete(id);
								}
							} else {
								GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
								gasStaytimeEntity.setHandleFlag("数据缺失不全?");
								BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
								gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
								gasStaytimeService.realDelete(id);
							}
						} else {
							GasStaytimeHistoryEntity gasStaytimeHistoryEntity = new GasStaytimeHistoryEntity();
							gasStaytimeEntity.setHandleFlag("int转换异常:" + messageAreanumber);
							BeanUtils.copyProperties(gasStaytimeEntity, gasStaytimeHistoryEntity);
							gasStaytimeHistoryService.saveOrUpdate(gasStaytimeHistoryEntity);
							gasStaytimeService.realDelete(id);
						}
					}
				}
			}
		}
	}
	
	
	private void pushZN(GasStaytimeResultEntity gasStaytimeResultEntity,String messageDisappear,String messageAppear,String messageRuleid,GasStationinfoEntity gasStationinfoEntity) throws ParseException {
		DynamicDataSourceContextHolder.clear();

		LocalDate today = LocalDate.now();
		int year = today.getYear();
		int month = today.getMonthValue();
		String yearStr = year + "";
		String monthStr = "";
		if (month < 10) {
			monthStr = "0" + month;
		} else {
			monthStr = month + "";
		}

		String vehicleType = "";
		if ("汽油".equals(gasStaytimeResultEntity.getOils())) {
			vehicleType = "1";
		} else {
			vehicleType = "8";
		}

		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss.SSS");
		sdf.setLenient(false); // 设置严格模式，不允许解析不严格对应格式的日期

		long costTime = (sdf.parse(messageDisappear).getTime()
				- sdf.parse(messageAppear).getTime()) / 1000l;

		String thirdPartyId = gasStationinfoEntity.getThirdPartyId();
		
		ZnGasStation znGasStation = znGasStationMapper.selectById(thirdPartyId);

		if (znGasStation.getIsNormal() == 1
				&& znGasStation.getIsValid() == 1
				&& !messageRuleid.equals(Constants.GAS_CAR_MOTO)) {
			// 排除摩托车
			SimpleDateFormat _sdf = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			Date time = _sdf.parse(gasStaytimeResultEntity.getTime());
			Timestamp _time = new Timestamp(time.getTime());

			String sql = "INSERT INTO gas_detection_out_1_" + yearStr + "_"
					+ monthStr + " "
					+ "(id, annotationId, stationId, indexCode, startImg, endImg, startTime, endTime, createTime, costTime, vehicleType)"
					+ " VALUES ('" + TsBqUtils.getUUID() + "', '"
					+ TsBqUtils.getUUID() + "', "
					+ gasStationinfoEntity.getThirdPartyId()
					+ ", 'indexCode', '"
					+ gasStaytimeResultEntity.getImage() + "', '"
					+ gasStaytimeResultEntity.getImage1() + "', '"
					+ gasStaytimeResultEntity.getMessageAppear() + "', '"
					+ gasStaytimeResultEntity.getMessageDisappear() + "', '"
					+ _time + "', " + costTime + ", " + vehicleType + ")";
			logger.debug("执行sql:" + sql);
			gasDetectionSqlMapper.gasDetectionInsertInto(sql);
		} else {
			logger.debug(
					"加油站数据不传IsNormalIsValid:" + znGasStation.getIsNormal()
							+ znGasStation.getIsValid());
		}
		
	}

	private void pushProvince(GasStaytimeResultEntity gasStaytimeResultEntity) {
		DynamicDataSourceContextHolder.clear();
		ProvinceGasStaytimeResultEntity entity = new ProvinceGasStaytimeResultEntity();
		BeanUtils.copyProperties(gasStaytimeResultEntity, entity);
		provinceGasStaytimeResultMapper.insert(entity);
	}
}